#!/bin/bash
# 备份 MySQL 数据库并清理旧文件
# 使用方法: crontab 30 3 * * * source $HOME/.bash_profile && sh /sumz/script/mysql_bak.sh >> /sumz/mysql_bak.log 2>&1

# 启用 pipefail，确保管道中任一命令失败时退出状态非 0
set -o pipefail

# 配置
BACKUP_DIR="/sumz/data_bak/mysql_bak_file"  # 备份根目录
PROJECTS=("nacos_config" "xxl_job") # 需要备份的数据库
MYSQL_USER="root"                           # MySQL 用户名
MYSQL_PASS="123456"                      # MySQL 密码（建议改为环境变量）
KUBECTL_CMD="/usr/local/bin/kubectl"        # kubectl 路径
NAMESPACE="base"                            # Kubernetes 命名空间
POD_NAME="mysql-0"                          # MySQL Pod 名称
KEEP_DAYS=30                                # 保留天数
KEEP_FRIDAY=true                            # 是否保留星期五的备份

# 检查依赖
if ! command -v "$KUBECTL_CMD" &> /dev/null; then
    echo "错误: 未找到 kubectl，请检查路径: $KUBECTL_CMD"
    exit 1
fi

# 备份函数
backup_database() {
    local db_name="$1"
    local backup_path="$BACKUP_DIR/$db_name"
    local timestamp=$(date +%Y-%m-%d_%H_%M)
    local backup_file="$backup_path/${db_name}_${timestamp}.sql.gz"

    mkdir -p "$backup_path" || {
        echo "错误: 创建目录 $backup_path 失败"
        return 1
    }

    echo "开始备份 $db_name 到 $backup_file"
    # 执行备份命令，确保完整管道的退出状态被检查
    $KUBECTL_CMD exec "$POD_NAME" -n "$NAMESPACE" -ti -- \
        mysqldump -B "$db_name" -u"$MYSQL_USER" -p"$MYSQL_PASS" 2>/tmp/mysql_bak_err | gzip > "$backup_file" 2>/dev/null

    local exit_code=$?
    if [ $exit_code -eq 0 ]; then
        echo "备份 $db_name 成功"
    else
        echo "错误: 备份 $db_name 失败，退出码: $exit_code"
        if [ -s /tmp/mysql_bak_err ]; then
            echo "错误详情: $(cat /tmp/mysql_bak_err)"
        fi
        rm -f /tmp/mysql_bak_err
        return 1
    fi
}

# 删除旧备份函数
clean_old_backups() {
    local db_name="$1"
    local backup_path="$BACKUP_DIR/$db_name"

    if [ ! -d "$backup_path" ]; then
        echo "警告: 目录 $backup_path 不存在，跳过清理"
        return 0
    fi

    echo "清理 $db_name 的旧备份（保留 $KEEP_DAYS 天，星期五备份除外）"
    find "$backup_path" -type f -name "*.sql.gz" -mtime +"$KEEP_DAYS" | while read -r file; do
        file_day=$(date -r "$file" +%w)
        if [ "$KEEP_FRIDAY" = true ] && [ "$file_day" -eq 5 ]; then
            echo "保留星期五备份: $file"
        else
            rm -f "$file" && echo "删除旧备份: $file"
        fi
    done
}

# 主逻辑
for db in "${PROJECTS[@]}"; do
    backup_database "$db"
    clean_old_backups "$db"
done

echo "备份和清理完成: $(date +%Y-%m-%d_%H:%M:%S)"